package com.stylefeng.guns.rest.common.utils.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import org.apache.commons.logging.Log;

/**
 * Created by ASUS-PC on 2019/3/26.
 */
public class JpushUtils {
    private static Log logger = org.apache.commons.logging.LogFactory.getLog(JpushUtils.class);
    private static String APP_KEY = "95b9e24ba7be195a9845d855";
    private static String MASTER_SECRET = "c77488916a3f0280eb91ada7";


    public static void sendPushMessageByAlias(String alias,String userName,int type){
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, ClientConfig.getInstance());

        // For push, all you need do is to build PushPayload object.
        PushPayload payload = null;
        if(type ==3){//点赞
            payload = buildPushObject_all_all_alert(alias,userName,3);
        }else if(type==1){
            payload = buildPushObject_all_all_alert(alias,userName,1);
        }else {//评论
            payload = buildPushObject_all_all_alert(alias,userName,2);
        }


        try {
            PushResult result = jpushClient.sendPush(payload);
            logger.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            logger.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            logger.error("Should review the error, and fix the request", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
        }
    }

    public static PushPayload buildPushObject_all_all_alert(String alias,String userName,int type) {
        if(type ==3){
            return PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.alias(alias))
                    .setNotification(Notification.alert(userName+"点赞了你"))
                    .build();
        }else if(type == 1){
            return PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.alias(alias))
                    .setNotification(Notification.alert(userName+"关注了你"))
                    .build();
        }
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.alert(userName+"评论了你"))
                .build();
    }
}
